import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

// 模拟球员数据
const mockPlayers = [
  { id: 1, name: "梅西", number: 10 },
  { id: 2, name: "C罗", number: 7 },
  { id: 3, name: "内马尔", number: 11 },
  { id: 4, name: "姆巴佩", number: 7 },
  { id: 5, name: "哈兰德", number: 9 },
  { id: 6, name: "德布劳内", number: 17 },
  { id: 7, name: "莫德里奇", number: 10 },
  { id: 8, name: "本泽马", number: 9 },
  { id: 9, name: "莱万多夫斯基", number: 9 },
  { id: 10, name: "萨拉赫", number: 11 },
  { id: 11, name: "马内", number: 10 },
  { id: 12, name: "凯恩", number: 9 },
  { id: 13, name: "孙兴慜", number: 7 },
  { id: 14, name: "范迪克", number: 4 },
  { id: 15, name: "拉莫斯", number: 4 },
  { id: 16, name: "皮克", number: 3 },
  { id: 17, name: "布斯克茨", number: 5 },
  { id: 18, name: "克罗斯", number: 8 },
  { id: 19, name: "卡塞米罗", number: 14 },
  { id: 20, name: "坎特", number: 7 },
  { id: 21, name: "博格巴", number: 6 },
  { id: 22, name: "德容", number: 21 },
  { id: 23, name: "佩德里", number: 8 },
  { id: 24, name: "加维", number: 30 },
  { id: 25, name: "维尼修斯", number: 20 },
  { id: 26, name: "罗德里戈", number: 11 },
  { id: 27, name: "巴尔韦德", number: 15 },
  { id: 28, name: "楚阿梅尼", number: 18 },
  { id: 29, name: "阿拉巴", number: 4 },
  { id: 30, name: "米利唐", number: 3 }
];

// 模拟异步获取球员列表
export const fetchPlayers = createAsyncThunk(
  'players/fetchPlayers',
  async (_, { rejectWithValue }) => {
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      return mockPlayers;
    } catch (error) {
      return rejectWithValue('获取球员列表失败');
    }
  }
);

// 模拟搜索球员
export const searchPlayers = createAsyncThunk(
  'players/searchPlayers',
  async (searchTerm, { rejectWithValue }) => {
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const filteredPlayers = mockPlayers.filter(player => {
        const searchLower = searchTerm.toLowerCase();
        return (
          player.name.toLowerCase().includes(searchLower) ||
          player.number.toString().includes(searchTerm)
        );
      });
      
      return filteredPlayers;
    } catch (error) {
      return rejectWithValue('搜索球员失败');
    }
  }
);

// 模拟排序球员
export const sortPlayers = createAsyncThunk(
  'players/sortPlayers',
  async ({ sortType, sortOrder }, { rejectWithValue }) => {
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      let sortedPlayers = [...mockPlayers];
      
      if (sortType === 'number') {
        sortedPlayers.sort((a, b) => {
          return sortOrder === 'asc' ? a.number - b.number : b.number - a.number;
        });
      } else if (sortType === 'name') {
        sortedPlayers.sort((a, b) => {
          const result = a.name.localeCompare(b.name, 'zh-CN');
          return sortOrder === 'asc' ? result : -result;
        });
      }
      
      return sortedPlayers;
    } catch (error) {
      return rejectWithValue('排序球员失败');
    }
  }
);

const playerSlice = createSlice({
  name: 'players',
  initialState: {
    players: [],
    filteredPlayers: [],
    searchTerm: '',
    sortType: '',
    sortOrder: 'asc',
    loading: false,
    error: null,
    hasMore: true,
    currentPage: 1,
    pageSize: 20,
  },
  reducers: {
    setSearchTerm: (state, action) => {
      state.searchTerm = action.payload;
    },
    setSort: (state, action) => {
      state.sortType = action.payload.type;
      state.sortOrder = action.payload.order;
    },
    clearSearch: (state) => {
      state.searchTerm = '';
      state.filteredPlayers = state.players;
    },
    clearSort: (state) => {
      state.sortType = '';
      state.sortOrder = 'asc';
      state.filteredPlayers = state.players;
    },
    resetPlayers: (state) => {
      state.players = [];
      state.filteredPlayers = [];
      state.searchTerm = '';
      state.sortType = '';
      state.sortOrder = 'asc';
      state.currentPage = 1;
      state.hasMore = true;
    },
  },
  extraReducers: (builder) => {
    builder
      // 获取球员列表
      .addCase(fetchPlayers.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchPlayers.fulfilled, (state, action) => {
        state.loading = false;
        state.players = action.payload;
        state.filteredPlayers = action.payload;
        state.error = null;
      })
      .addCase(fetchPlayers.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      // 搜索球员
      .addCase(searchPlayers.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(searchPlayers.fulfilled, (state, action) => {
        state.loading = false;
        state.filteredPlayers = action.payload;
        state.error = null;
      })
      .addCase(searchPlayers.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      // 排序球员
      .addCase(sortPlayers.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(sortPlayers.fulfilled, (state, action) => {
        state.loading = false;
        state.filteredPlayers = action.payload;
        state.error = null;
      })
      .addCase(sortPlayers.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      });
  },
});

export const { 
  setSearchTerm, 
  setSort, 
  clearSearch, 
  clearSort, 
  resetPlayers 
} = playerSlice.actions;

export default playerSlice.reducer;
